<template>
  <el-dialog
      v-model="visible"
      :title="dialogTitle"
      width="640px"
      class="dialog"
      destroy-on-close
      @closed="handleClosed"
  >
    <el-form
        :model="formData"
        label-width="100px"
        ref="formRef"
        :rules="rules"
        class="form"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="组织名称" prop="orgName" required>
            <el-input
                v-model="formData.orgName"
                placeholder="请输入组织名称"
                clearable
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="组织编码" prop="orgCode" required>
            <el-input :readonly="!!formData.orgId"
                v-model="formData.orgCode"
                placeholder="请输入组织编码"
                clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false" round>取 消</el-button>
        <el-button type="primary" @click="submitForm" round>提 交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { OrgItem } from "@/views/org/org"

const emit = defineEmits(['submit'])

const formRef = ref<FormInstance>()

const formData = ref<OrgItem>({
  orgId: null,
  orgCode: "",
  orgName: "",
  orgPid: null
})

const rules: FormRules = {
  orgCode: [
    { required: true, message: '请输入组织编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50之间', trigger: 'blur' }
  ],
  orgName: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50之间', trigger: 'blur' }
  ],
}

const visible = ref(false)
const dialogTitle = ref('')

const openDialog = (orgPid:number,rowData?: OrgItem) => {
  if (rowData && rowData.orgId) {
    dialogTitle.value = '修改组织'
    formData.value = { ...rowData }
    formData.value.orgPid = orgPid
  } else {
    dialogTitle.value = '新增组织'
    formData.value = {
      orgId: null,
      orgCode: "",
      orgName: "",
      orgPid: orgPid
    }
  }
  visible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    emit('submit', formData.value)
    visible.value = false
  } catch (error) {
    console.log('Form validation failed')
  }
}

const handleClosed = () => {
  formRef.value?.clearValidate()
}

defineExpose({ openDialog })
</script>

<style scoped>
.dialog {
  border-radius: 12px;
}

.form {
  padding: 10px 10px 0 0;
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
</style>
